const JWT = require("../../utils/jwt");
const MYSQL = require("../../sql/mysql");
const MYSQLConfig = require("../../sql/database");
const SQLName = MYSQLConfig.datasheetName.user_token;
// 系统配置信息
const Config = require("../../config");
const DayJs = require("dayjs");
/**
 * 创建密钥
 * @param {*} userInfo
 * @returns
 */
module.exports = async (userInfo = {}) => {
  try {
    let SecretKeyConfig = Config.SecretKey;
    let { way } = SecretKeyConfig;
    let { user } = userInfo;
    // 密钥类型
    let secretKetType = null;
    // 密钥
    let secretKey = null;

    // 当前时间
    let now_date = DayJs(Date.now()).valueOf();
    // 密钥创建时间
    let create_date = now_date;
    // 密钥过期时间
    let expired_date = null;

    // 返回数据对象
    let returnData = {};

    if (way == "token") {
      //   token配置对象
      let tokenConfig = SecretKeyConfig.type.token;
      let { expired } = tokenConfig;
      expired_date = now_date + expired;
      let createTokenInfo = JWT.createToken(userInfo);
      let token = createTokenInfo.secretkey;
      secretKey = token;
      returnData.token = token;
      secretKetType = 0;
    } else if (way == "cookie") {
      let cookie = "tesk cookie";
      returnData.cookie = cookie;
      secretKey = cookie;
      secretKetType = 1;
    } else {
      throw {
        code: 500,
        msg: "密钥创建失败,不支持的密钥类型",
        statusCode: 500,
      };
    }
    // 删除数据库中已经过期的token记录
    await MYSQL.promise().query(
      `DELETE FROM ${SQLName} WHERE expired_date < '${create_date}' `
    );
    // 将本次生成的token存入数据库中
    await MYSQL.promise().query(`INSERT INTO ${SQLName} SET ?`, {
      type: secretKetType,
      user,
      userInfo: JSON.stringify(userInfo),
      secretKey,
      expired_date,
      create_date,
    });
    
    // 返回数据
    return {
      code: 0,
      msg: "操作成功",
      data: {
       
        secretKey,
        expired_date,
        create_date,
        ...returnData,
      },
    };
  } catch (error) {
    console.log(error);
    console.log("操作失败,创建token时发生错误 -a");
    throw error;
  }
};
